package leetcode.code0233;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int countDigitOne(int n) {
		int ans = 0;
		int cur = 0;
		int curLeft = 0;
		int curRight = 0;
		int mul = 1;
		int curOne = 0;
		int num = n;
		while (num > 0) {
			cur = num % 10;// 当前数字
			curLeft = num / 10;// 当前数字左边剩余数字
			curRight = n % mul;// 当前数字原数右边数字
			if (cur == 0) {// 当前位置0
				// cur左边可性能从1到curLeft，共curLeft种，当前是0，左不允许0。右边出现种数是[0,mul-1]，共mul种
				curOne = curLeft * mul;
			} else if (cur == 1) {
				// xx1yy，到xx099累计出现curLeft * mul次，从xx099到xx1yy。yy是多少就出现yy+1个。
				curOne = curLeft * mul + curRight + 1;
			} else {
				// xx2yy，在中间出现1的次数与xx199。是一致的。左边可以是[0,curLeft],右边[0,mul-1]
				curOne = (curLeft + 1) * mul;
			}
			ans += curOne;
			num = curLeft;
			mul *= 10;
		}
		return ans;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(21, this.countDigitOne(100));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(23, this.countDigitOne(101));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(244, this.countDigitOne(711));

	}

	@Override
	public void debug4() {
		HelpDebug.compare(28744, this.countDigitOne(45711));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
